<%@ path=/confile/${filename}%>
<%
	param_string(id);
	param_string(name);
	param_string(level);
	param_string(title);
	param_string(folder);
	param_string(deficon);

	if (name.empty())
	{
		clearResponse();

		return XG_PARAMERR;
	}

	if (id.empty() && folder.empty())
	{
		clearResponse();

		return XG_PARAMERR;
	}
	
	try
	{
		checkLogin();
	}
	catch(Exception e)
	{
		out << "<script>sessionTimeout()</script>";

		return XG_NOTFOUND;
	}

	int route = 0;

	try
	{
		checkSystemRight();

		route = app->getRouteSwitch();
	}
	catch(Exception e)
	{
		route = 0;
	}

	if (deficon.empty()) deficon = "/res/img/note/configure.png";
%>

<style>
#CodeContentDiv{
	margin-top: 2px;
	border: 1px solid #DDD;
}
.CodeMirror{
	background: rgba(255, 255, 255, 0.6);
}
.CodeMirror-gutters{
	background: rgba(255, 255, 255, 0.7);
}
</style>

<table id='NoteEditTable'>
	<tr>
		<td id='NoteListTd'>
			<div id='NoteListDiv'>
				<table id='NoteListTable'></table>
			</div>
		</td>
		<td id='NoteEditTd'>
			<table>
				<tr>
					<td>
						<v-text id='NoteTitleText' title='<%=name%>名称' maxlength='20'></v-text>
						<v-select id='NoteLevelSelect' title='<%=name%>级别' option='系统|普通|推荐|公开'></v-select>
					</td>
					<td style='padding-left:16px'>
						<span title='点击上传<%=name%>图标' id='NoteIcon'></span>
					</td>
					<td>
						<button class='TextButton' style='margin-left:24px' id='SaveNoteButton'>保存</button>
						<button class='TextButton' style='margin-left:4px;color:#008800' id='AddNoteButton'>新建</button>
						<button class='TextButton' style='margin-left:4px;color:#DD2233' id='DeleteNoteButton'>删除</button>
						<%if (folder == "WEBPAGE"){%>
							<button class='TextButton' style='margin-left:12px;color:#DD2233' id='SyncNoteButton'><%=(route?"发布":"同步")%>配置</button>
						<%}%>
						<button class='TextButton' style='margin-left:12px' id='CopyNoteLinkButton' title='点击复制分享链接'>分享链接</button>
					</td>
					<td>
					</td>
				</tr>
			</table>
			<div id='CodeContentDiv'><textarea id='NoteContentText'></textarea></div>
		</td>
	</tr>
</table>

<script>
{
	getVue('NoteEditTable');

<%if (title.length() > 0 || id.length() > 0){%>
	$('#DeleteNoteButton').attr('disabled', true);
	$('#NoteLevelSelect').attr('disabled', true);
	$('#NoteListTd').hide();

	<%if (id.empty()){%>
		$('#NoteTitleText').attr('disabled', true);
	<%}%>
<%}%>

	var param = null;
	var curid = null;
	var notepad = null;
	var curicon = null;
	var curtitle = null;
	var curlevel = null;
	var titlelist = null;
	var uploadicon = null;
	var curcontent = null;
	var curiconbtn = null;
	var curnoteitem = null;
	var curdatetime = null;
	var selnoteitem = null;

	initNotepad();

	$('#NoteLevelSelect option:first').attr('disabled', true);

	var menubox = new ContextMenu(['前移', '后移'], function(text, elem){
		let arr = [];
		let item = $.pack(getContextMenuView());

		if (text == '前移'){
			item.prev().insertAfter(item);
		}
		else{
			item.next().insertBefore(item);
		}

		item.parent().children().each(function(){
			arr.push($(this).children('td:last').children('font:first').text());
		});

		getHttpResult('/confile/editnote', {flag: 'M', folder: '<%=folder%>', title: arr.join(',')});
	});

	var uploadimage = new UploadImageWidget('NoteIcon', '<%=name%>图标', '14px', 1024 * 1024, true);

	uploadimage.callback(function(data){
		if (data == null || data.code < 0){
			showErrorToast('图片上传失败');
		}
		else{
			uploadicon = data.url;
		}
	});

	uploadimage.image.parent().click(function(){
		var iconpick = new IconPicker(uploadimage.image, 'note');
		
		uploadimage.image.blur(function(){
			uploadicon = true;
			iconpick.hide();
		});
	});

	function modifyNotepad(){
		var width = getClientWidth();
		var height = getClientHeight();

		var cx = width - 200;
		var cy = height - 97;

		if (getSideWidth) cx -= getSideWidth();

		$('#CodeContentDiv').width(cx).height(cy);
		
		$('#NoteListDiv').height(cy + 29);

		notepad.setSize('100%','100%');
	}
	function initNotepad(){
		notepad = CodeMirror.fromTextArea(document.getElementById('NoteContentText'), {
			mode: 'shell',
			onBlur: notepadBlur,
			tabSize: 4,
			indentUnit: 4,
			inputStyle: 'textarea',
			foldGutter: true,
			lineNumbers: true,
			lineWrapping: true,
			matchBrackets: true,
			indentWithTabs: true,
			styleActiveLine: true,
			showCursorWhenSelecting: true,
			gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
		});
		
		modifyNotepad();

		notepad.on('blur', notepadBlur);

		return notepad;
	}

	function addNoteResult(flag){
		if (flag == 1) return editNoteItem(param, 'A');
	}

	function delNoteResult(flag){
		if (flag == 1) return editNoteItem(param, 'D');
	}

	function delNoteFolderResult(flag){
		if (flag == 1) return editNoteItem(param, 'R');
	}

	function getContent(msg){
		return notepad ? notepad.getValue() : null;
	}

	function setContent(msg){
		notepad.setValue(msg);
		setNotepadFocus();
		modifyNotepad();
	}

	function setNotepadFocus(){
		notepadBlur(notepad);
	}

	function notepadBlur(notepad){
		var content = getContent();
		if (content != (curcontent || '')){
			setSaveNeeded(function(func){
				var icon = getBackgroundImage(uploadimage.image[0]);
				var level = $('#NoteLevelSelect').val();
				var title = $('#NoteTitleText').val();

				setSaveNeeded(null);

				param = {};
				param['id'] = curid;
				param['level'] = level;
				param['title'] = title;
				param['content'] = content;
				param['folder'] = '<%=folder%>';
				
				if ((len = strlen(title)) == 0){
					showToast('<%=name%>名称不能为空');
					$('#NoteTitleText').focus();
				}
				else if (len > 24){
					showToast('<%=name%>名称最多12个汉字或24个英文字母');
					$('#NoteTitleText').focus();
				}
				else if ((len = strlen(content)) == 0){
					showToast('<%=name%>内容不能为空');
					setNotepadFocus();
				}
				else if (len > 1024 * 1024){
					showToast('<%=name%>内容太长');
					setNotepadFocus();
				}
				else
				{
					param['icon'] = getString(icon);

					if (title == curtitle){
						showConfirmMessage('<%=name%>内容已修改，是否马上保存？', '保存选项', function(flag){
							if (flag == 1) editNoteItem(param, 'U');
							if (func) func();
						});
					}
					else{
<%if (title.length() > 0 || id.length() > 0){%>
						showConfirmMessage('<%=name%>内容已修改，是否马上保存？', '保存选项', function(flag){
							if (flag == 1) editNoteItem(param, 'U');
							if (func) func();
						});
<%}else{%>
						showConfirmMessage('<%=name%>名称已修改，是否新建<%=name%>？', '是否新建', function(flag){
							if (flag == 1) editNoteItem(param, 'A');
							if (func) func();
						});
<%}%>
					}

					return true;
				}
				
				if (func) func();
				
				return false;
			});
		}
	}

	function loadNoteItem(flag){
		$('#NoteEditTable').hide();

		param = {};
		param['id'] = '<%=id%>';
		param['level'] = '<%=level%>';
		param['title'] = '<%=title%>';
		param['folder'] = '<%=folder%>';

		$('#CopyNoteLinkButton').attr('disabled', true);
		$('#NoteLevelSelect').val(1);
		titlelist = '|';

		getHttpResult('/confile/getnotelist', param, function(data){
			$('#NoteListTable').html('');

			if (data.code == XG_TIMEOUT){
				sessionTimeout();
			}
			else if (data.code == XG_AUTHFAIL){
				showNoAccessToast();
			}
			else if (data.code < 0){
				showToast('加载数据失败');
			}
			else if (data.code == 0){
<%if (title.length() > 0 || id.length() > 0){%>
				showToast('没有找到<%=name%>数据');
<%}else if (folder == "WEBPAGE"){%>
				$('#NoteLevelSelect').val(3);
				$('#DeleteNoteButton').attr('disabled', true);
				if (flag == 'D'){
					curid = null;
				}
<%}else{%>
				if (flag == 'D'){
					showConfirmMessage('目录[' + '<%=folder%>' + ']' + '无<%=name%>信息。<br>是否决定删除该目录？', '删除目录', delNoteFolderResult);
					curid = null;
					flag = false;
				}
<%}%>
				uploadimage.image.css('background-image', 'url(<%=deficon%>)');
				$('#NoteTitleText').val('');
				$('#NoteEditTable').show();
				setContent('');
			}
			else{
				curdatetime = null;
				selnoteitem = null;

				$.each(data.list, function(idx, item){
					titlelist += item.title + '|';
					addNoteItem(item.id, item.title, item.icon, item.level, item.statetime);
				});
				
				selectNoteItem(selnoteitem);
				
				$(".NotepadItem").each(function(){
					menubox.bind(this);
				});
			}
		});

		return flag;
	}
	function updateNoteInfo(note, level, title){
		level = getString(level);
		title = '<font>' + title + '</font>';
		
		if (level == '0'){
			note.children().last().html(title + '<span>系统</span>').children('span').css('color', '#EE2233');
		}
		else if (level =='1'){
			note.children().last().html(title + '<span>普通</span>').children('span').css('color', '#000000');
		}
		else if (level =='2'){
			note.children().last().html(title + '<span>推荐</span>').children('span').css('color', '#000000').css('font-weight', 'bold');
		}
		else{
			note.children().last().html(title + '<span>公开</span>').children('span').css('color', '#22BB22');
		}
	}
	function addNoteItem(id, title, icon, level, statetime){
		$('#NoteListTable').append("<tr class='NotepadItem' id='Note" + id + "' value='" + id + "'><td class='NoteIconButton' style='background-image:url(" + icon + ")'></td><td></td></tr>");
		
		var note = $('.NotepadItem').last();
		
		if (curdatetime == null || curdatetime < statetime || selnoteitem == null){
			curdatetime = statetime;
			selnoteitem = note;
		}
		
		updateNoteInfo(note, level, title);

		return note.click(function(){
			selectNoteItem($(this));
		});
	}
	function editNoteItem(param, flag){
		if (flag == 'A') param['id'] = '';

		if (flag == 'C' || flag == 'D' || flag == 'R'){
			param['title'] = '';
			param['content'] = '';
		}

		param['flag'] = flag;
		param['deficon'] = '<%=deficon%>';
		
		if (flag == 'U' && uploadicon == null) param['icon'] = '';

		getHttpResult('/confile/editnote', param, function(data){
			if (data.code == XG_TIMEOUT){
				sessionTimeout();
			}
			else if (data.code == XG_AUTHFAIL){
				showNoAccessToast();
			}
			else if (data.code < 0){
				if (flag == 'A'){
					showToast('新建<%=name%>失败');
				}
				else if (flag == 'D'){
					showToast('删除<%=name%>失败');
				}
				else if (flag == 'U'){
					showToast('修改<%=name%>失败');
				}
				else if (flag == 'R'){
					showToast('删除目录失败');
				}
				else{
					showToast('保存<%=name%>失败');
				}
			}
			else{
				setSaveNeeded(null);
				
				if (flag == 'R'){
					selectMenu(curmenuitem, true);
				}
				else if (flag == 'A'){
					showToast('新建<%=name%>成功');
					titlelist += param['title'] + '|';
					selectNoteItem(addNoteItem(data.id, param['title'], data.icon, param['level'], data.statetime));
					menubox.bind('Note' + data.id);
				}
				else if (flag == 'U'){
					showToast('<%=name%>保存成功');
					
					if (curtitle != param['title']){
						var pos = titlelist.indexOf('|' + curtitle + '|');
						if (pos >= 0){
							titlelist = titlelist.substring(0, pos) + param['title'] + titlelist.substring(pos + curtitle.length);
						}
					}
					
					curcontent = param['content'] || curcontent;
					curtitle = param['title'];
					curlevel = param['level'];
					curicon = param['icon'];

					if (strlen(data.icon) > 0){
						uploadimage.image.css('background-image', 'url(' + data.icon + ')');
						curicon = data.icon;
					}

					if (strlen(curicon) > 0){
						curiconbtn.css('background-image', 'url(' + curicon + ')');
					}
					
					updateNoteInfo(curnoteitem, curlevel, curtitle);
				}
				else{
					flag = loadNoteItem(flag);
				}
			}
		});
		
		return flag;
	}
	function selectNoteItem(note){
		if (saveneeded){
			saveneeded(function(){
				selectNoteItem(note);
			});
			
			saveneeded = null;
			return true;
		}

		$('.NotepadItem').css('background', 'none');
		note.css('backgroundColor', 'rgba(0, 0, 0, 0.3)');
		curiconbtn = note.find('.NoteIconButton');
		id = note.attr('value');
		curnoteitem = note;
		uploadicon = null;
		curcontent = null;
		curtitle = null;
		curlevel = null;
		curid = null;

		if (strlen(id) == 0){
			selectMenu(curmenuitem, true);
		}
		else{
			showToastMessage('正在加载数据...');
			$('#NoteTitleText').val('');
			param = {};
			param['id'] = id;
			getHttpResult('/confile/getnotecontent', param, function(data){
				hideToastBox();
				if (data.code == XG_TIMEOUT){
					sessionTimeout();
				}
				else if (data.code == XG_AUTHFAIL){
					showNoAccessToast();
				}
				else if (data.code < 0){
					showToast('加载数据失败');
				}
				else{
					curcontent = data.content;
					curtitle = data.title;
					curlevel = data.level;
					curicon = data.icon;

					uploadimage.image.css('background-image', 'url(' + data.icon + ')');
					$('#CopyNoteLinkButton').removeAttr('disabled');
					$('#NoteLevelSelect').val(curlevel);
					$('#NoteTitleText').val(curtitle);
					$('#NoteEditTable').show();

					setContent(curcontent);

					if (curid == null && navigator.userAgent.toLowerCase().indexOf("firefox") >= 0){
						notepad.fullscreen(true);
						notepad.fullscreen(false);
					}
					
					curid = data.id;
					
<%if (title.empty() && id.empty()){%>
					if (curlevel == 0){
						$('#DeleteNoteButton').attr('disabled', true);
						$('#NoteLevelSelect').attr('disabled', true);
						$('#NoteTitleText').attr('disabled', true);
					}
					else{
						$('#DeleteNoteButton').removeAttr('disabled');
						$('#NoteLevelSelect').removeAttr('disabled');
						$('#NoteTitleText').removeAttr('disabled');
						$('#NoteIcon').removeAttr('disabled');
					}
<%}%>
				}
			}, true);
		}
	}

	$('#DeleteNoteButton').click(function(){
		if (curid == null){
			showConfirmMessage('目录[' + '<%=folder%>' + ']' + '无<%=name%>信息。<br>是否决定删除该目录？', '删除目录', delNoteFolderResult);
		}
		else{
			param = {};
			param['id'] = curid;
			param['folder'] = '<%=folder%>';
			showConfirmMessage('是否决定删除当前<%=name%>？', '删除<%=name%>', delNoteResult);
		}
	});

	$('#AddNoteButton').click(function(){
		var uploadbutton = null;

		showConfirmMessage("<table id='AddNoteTable' class='DialogTable'><tr><td><v-select id='AddNoteLevelSelect' title='<%=name%>级别' option='系统|普通|推荐|公开'></v-select></td></tr><tr><td><v-text id='AddNoteTitleText' title='<%=name%>名称' size='14' maxlength='20'></v-text></td></tr></table>", '添加<%=name%>', function(flag){
			if (flag == 0) return true;
			
			var title = $('#AddNoteTitleText').val();
			var level = $('#AddNoteLevelSelect').val();

			if ((len = strlen(title)) == 0){
				$('#AddNoteTitleText').focus();
				return false;
			}
			else if (len > 24){
				setMessageErrorText('<%=name%>名称太长', $('#AddNoteTitleText'));
				return false;
			}
			else if (!isFileName(title)){
				setMessageErrorText('名称不能有特殊字符', $('#AddNoteTitleText'));
				return false;
			}
			else if (titlelist.indexOf('|' + title + '|') >= 0){
				setMessageErrorText('名称与现有<%=name%>冲突', $('#AddNoteTitleText'));
				return false;
			}

			param = {};
			param['level'] = level;
			param['title'] = title;
			param['folder'] = '<%=folder%>';

			return editNoteItem(param, 'A');
		});

<%if (folder == "WEBPAGE"){%>
		$('#AddNoteLevelSelect').val(3);
<%}else{%>
		$('#AddNoteLevelSelect').val(1).children('option').first().attr('disabled', true);
<%}%>
		$('#AddMenuTitleText').focus();
	});

	$('#SyncNoteButton').click(function(){
		var title = $('#NoteTitleText').val();

		if (strlen(title) == 0){
			showToast('<%=name%>名称不能为空');
			$('#NoteTitleText').focus();
			return false;
		}

<%if (route){%>
		var content = getContent();

		if (strlen(content) == 0){
			showToast('<%=name%>内容不能为空');
			setNotepadFocus();
			return false;
		}

		if (strlen(curid) == 0){
			showToast('请先保存<%=name%>');
			return false;
		}

		if (title != curtitle || content != curcontent){
			showToast('请先保存<%=name%>');
			return false;
		}

		showConfirmMessage('是否决定发布[' + title + ']配置？', '发布配置', function(flag){
			if (flag){
				var param = 'cmd=sync&type=confile&name=' + title;

				getHttpResult('/broadcast', {path: 'ExecModule', param: param}, function(data){
					if (data.code == XG_TIMEOUT){
						sessionTimeout();
					}
					else if (data.code == XG_AUTHFAIL){
						showNoAccessToast();
					}
					else if (data.code < 0){
						showToast('发布配置失败');
					}
					else{
						showToast('发布配置成功');
					}
				});
			}
		});
<%}else{%>
		getHttpResult('/execmodule', {cmd: 'get', type: 'confile', name: title}, function(data){
			if (data.code == XG_TIMEOUT){
				sessionTimeout();
			}
			else if (data.code == XG_AUTHFAIL){
				showNoAccessToast();
			}
			else if (data.code == XG_NOTFOUND){
				showToast('<%=name%>信息不存在');
			}
			else if (data.code < 0){
				showToast('同步<%=name%>信息失败');
			}
			else{
				showToast('同步<%=name%>成功');

				setContent(data.content);
			}
		});
<%}%>
	});

	$('#SaveNoteButton').click(function(){
		var icon = getBackgroundImage(uploadimage.image[0]);
		var level = $('#NoteLevelSelect').val();
		var title = $('#NoteTitleText').val();
		var content = getContent();

		setSaveNeeded(null);

		param = {};
		param['id'] = curid;
		param['level'] = level;
		param['title'] = title;
		param['content'] = content;
		param['folder'] = '<%=folder%>';

		if ((len = strlen(title)) == 0){
			showToast('<%=name%>名称不能为空');
			$('#NoteTitleText').focus();
		}
		else if (len > 24){
			showToast('<%=name%>名称最多12个汉字或24个英文字母');
			$('#NoteTitleText').focus();
		}
		else if ((len = strlen(content)) == 0){
			showToast('<%=name%>内容不能为空');
			setNotepadFocus();
		}
		else if (len > 1024 * 1024){
			showToast('<%=name%>内容太长，请分段保存');
			setNotepadFocus();
		}
		else{
			if (uploadicon == null) icon = curicon;

			param['icon'] = getString(icon);

			if (strlen(curid) == 0){
				editNoteItem(param, 'A');
			}
			else if (title == curtitle){
				if (icon == curicon && level == curlevel && content == curcontent){
					showToast('<%=name%>内容未更新');
				}
				else{
					if (content == curcontent) delete param['content'];
					editNoteItem(param, 'U');
				}
			}
			else{
				if (titlelist.indexOf('|' + title + '|') >= 0){
					showToast('<%=name%>名称与现有<%=name%>冲突');
					$('#NoteTitleText').focus();
				}
				else{
					editNoteItem(param, 'U');
				}
			}
		}
	});

	$('#CopyNoteLinkButton').click(function(){
		var link = '/confile/mainframe?path=/confile/sharenote' + encodeURIComponent('?flag=S&dbid=<%=token->getDataId()%>&id=' + curid) + '&title=' + encodeURIComponent(curtitle);
		var toast = "<a class='TextLink' href='" + link + "' target='_blank'><%=name%>分享链接已经复制到剪切板</a>";
		setClipboard(getHost() + link, toast);
	});

	loadNoteItem();
}
</script>